<?php
/*
Copyright (C) 2011  Benjamin Marchand

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
uses('model' . DS . 'connection_manager');

class UpdaterController extends Controller {
	var $name = 'Updater';
	var $components = array('RequestHandler','Session');
	var $helpers = array('Html','Javascript','Session','Js' => array('jquery'));
	var $uses = array("items");
	var $tables = array("items","mcgroups","mcrights","mctemplateplugins","mcusers","settings","users");
	
	function beforeFilter() {
	}
	
	function beforeRender() {
		$this->layout ='install';
		$this->set('title_for_layout', 'Webukkit Updater');		
	}
	
	function index() {
		$db = ConnectionManager::getDataSource('default');
		$tablesinbase = $this->getTables($db);
		foreach($this->tables as $table)
		{
			$created = in_array($table,$tablesinbase);
			$results[]=array("name"=>$table,"created"=>$created);
		}
		$this->set("missingitems",$this->_countmissingitems());
		$this->set("results",$results);
		$this->set("missingtemplates",$this->_getMissingTemplates());
	}
	
	function getTables($db)
	{
		$db->cacheSources=false;
		$tables = $db->listSources(false);
		return $tables;
	}
	
	function createtemplate()
	{
	$this->loadModel('mctemplateplugins');
	$this->autoRender = FALSE;
	$this->autoLayout = FALSE;
	$row = 1;
	$template = $this->params['form']['name'];
		if (($handle = fopen(ROOT.DS."mctemplateplugins.csv", "r")) !== FALSE) {
			while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
				$num = count($data);
				$row++;
				if ($row>2)
				{
					if ($data[$nameindex]==$template)
					{
						for ($c=0; $c < $num; $c++) {
						if (!stristr($fieldname[$c],'id'))
							$missing['mctemplateplugins'][$fieldname[$c]]=$data[$c];
						}
					};
				}
				else
				{
				for ($c=0; $c < $num; $c++) {
				if (stristr($data[$c],'name'))
					$nameindex = $c;
				$fieldname[$c] = $data[$c];
        		}
				$c = 0;
				}
			}
			if ($this->mctemplateplugins->save($missing))
				$this->set('message','Saving succeed');
			else
				$this->set('message','Error in saving!');
			fclose($handle);
		}
	else
	{
		$this->set('message','Error during the template reading');
	}
	$this->set("missingtemplates",$this->_getMissingTemplates());
	$this->render('/elements/updater_showmissingtemplates');
	}
	
	function _getMissingTemplates()
	{
	$missing = NULL;
	$this->loadModel('mctemplateplugins');
	// get the templates list
	$row = 1;
		if (($handle = fopen(ROOT.DS."sql".DS."mctemplateplugins.csv", "r")) !== FALSE) {
			while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
				$num = count($data);
				//echo "<p> $num champs à la ligne $row: <br /></p>\n";
				$row++;
				//echo $data[1];
				if ($row>2)
				{
					if (!$this->mctemplateplugins->findByName($data[$c]))
					{
						$missing[]=$data[$c];
					};
				}
				else
				{
				$c = 0;
					// we get the index for field 'name'
					while (!stristr($data[$c],'name'))
						$c++;
				}
			}
			fclose($handle);
		}
		return $missing;
	}
	
	function is_removeable($dir)
	{
		$folder = opendir($dir);
		while($file = readdir( $folder ))
			if($file != '.' && $file != '..' &&
		(is_dir($dir."/".$file) && !is_writable($dir."/".$file) ||
		(is_dir($dir."/".$file) && !$this->is_removeable($dir."/".$file))))
		{
			closedir($dir);
			return false;
		}
		closedir($dir);
		return true;
	}
	
	function createtable()
	{
		$this->autoRender = FALSE;
		$this->autoLayout = FALSE;
		$tablename = $this->params['form']['name'];
		$db = ConnectionManager::getDataSource('default');
		$db->cacheMethods = FALSE;
		$prefix = $this->Session->read('sqldatasource.prefix');

		$data = file_get_contents(ROOT.DS.'sql'.DS.$tablename.'.sql');
		if (!empty($prefix))
		{
			$data = str_replace("`".$tablename."`", "`".$prefix.$tablename."`", $data);
		}
		$this->__runSQLdata($db,$data);
		$tablesinbase = $this->getTables($db);
		foreach($this->tables as $table)
		{
			$created = in_array($table,$tablesinbase);
			$results[]=array("name"=>$table,"created"=>$created);
		}
		$this->set("results",$results);
		$this->render("/elements/updater_showmissingtable");
	}
	
	function _countmissingitems()
	{
		$itemsinbase = $this->items->find('count');
		$itemsfile = file_get_contents(ROOT.DS.'sql'.DS.'items.sql');
		$itemscount = substr_count($itemsfile,'INSERT IGNORE INTO');
		return $itemscount-$itemsinbase;
	}
	
	function injectItems()
	{
		$this->autoRender = FALSE;
		$this->autoLayout = FALSE;
		$prefix = $this->Session->read('sqldatasource.prefix');
		$data = file_get_contents(ROOT.DS.'sql'.DS.'items.sql');
		$db = ConnectionManager::getDataSource('default');
		if (!empty($prefix))
		{
			$data = str_replace("`items`", "`".$prefix."items`", $data);
		}
		$this->__runSQLdata($db,$data);
		$this->set("missingitems",$this->_countmissingitems());
		$this->render('/elements/updater_showmissingitems');
	}

	private function __runSQLfile($db, $fileName) {
		$success = true;
		$statements = file_get_contents($fileName);
		$statements = explode(';', $statements);
		foreach ($statements as $statement) {
			if (trim($statement) != '') {
				if (!$db->query($statement))
					$success = false;
			}
		}
		return $success;
	}
	
	private function __runSQLdata($db, $data) {
		$success = true;
		$statements = explode(';', $data);
		foreach ($statements as $statement) {
			if (trim($statement) != '') {
				//				file_put_contents('c:\temp\bukkit.log',$db->query($statement),FILE_APPEND);
				if (!$db->query($statement))
					$success = false;
			}
		}
		return $success;
	}

}
?>